//
//  HMUserAccountViewModel.swift
//  Weibo
//
//  Created by 米易雅克 on 16/4/13.
//  Copyright © 2016年 米易雅克. All rights reserved.
//

import UIKit
/// 专门处理 HMUserAccount 模型的相关操作,网络请求,字典转模型,归档,解档
class HMUserAccountViewModel: NSObject {
    
//    定一个单例
    static let sharedInstance = HMUserAccountViewModel()
    
    private override init() {
        super.init()
        
//        因为单例只加载一次
//        加载账号
        userAccount = loadUserAccount()
    }
    
    
    
// 获取账号模型
    var userAccount : HMUserAccount?
    
// 用户是否登陆
    var userLogin: Bool {
    
        get{
        
        return userAccount != nil
        }
    
    
    }
    
    
    //    获取accessToken
    //    "access_token" = "2.00v1vb4GNimhZC9d97a06459JAYFPD";
    
    func loadAccessToken(code: String,loadAccessTokenCallback:(error: NSError?) ->()){
        
        let urlStr = accessTokenURLString
        // 2.参数，字典
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": grant_type,
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        HMNetworkTool.sharedInstance.POST(urlStr, parameters: parameters, progress: nil, success: { (task, responseObjec) in
            
//            HMPrint("accessToken请求成功\(responseObjec)")
            // as: 表示类型转换
            // as?: 有可能转成功,有可能转失败
            // as!: 一定能转成成功,如果转换失败,直接挂了
            let result = responseObjec as? [String : AnyObject]
            
            if let dict = result {
                
                self.userAccount = HMUserAccount(dict: dict)
                
//                HMPrint("字典转换成功\(userAccount)")
                
//                let filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
//                NSKeyedArchiver.archiveRootObject(userAccount, toFile: filePath)
                self.saveUserAccount()
                
                loadAccessTokenCallback(error: nil)
            }
            
        }) { (task, error) in
            
//            HMPrint("accessToken请求失败\(error)")
            
            loadAccessTokenCallback(error: error)
        }
        
        
    }
    
    
//    保存账号模型-->归档
    private func saveUserAccount() {
    
        if let userAccount = self.userAccount {
//    归档
      NSKeyedArchiver.archiveRootObject(userAccount, toFile: filePath)
            
        }
    
    }
//    从沙盒中解析userAccount模型
    func loadUserAccount() ->HMUserAccount? {
        // 解档账号,有可能有,有可能没有

        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? HMUserAccount
        
        // 可选绑定, 判断账号是否有值,账号有值,判断是否过期
        
        if let account = userAccount where account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
//            HMPrint("没有过期\(account)")
            return account
        }
            return nil
    }

    //MARK: 获取用户信息
    func loadUserInfo(loadUserInfoCallBack :(error: NSError?) -> ()){
        
        //守卫
        guard let access_token = userAccount?.access_token else {
            
            HMPrint("userAccount?没有值,或者access_token没有值")
            return
            
        }
        
        guard let uid = userAccount?.uid else{
        
        HMPrint("userAccount?没有值,或者uid没有值")
            return
        }
        let url = "https://api.weibo.com/2/users/show.json"
//        参数
        let parameters = [
        
            "access_token" : access_token,
            "uid" : uid
        ]
        
        
        HMNetworkTool.sharedInstance.GET(url, parameters: parameters, success: { (task, responseObject) in
//            HMPrint("加载用户信息成功:\(responseObject)")
            
            if let dict = responseObject as? [String : AnyObject]{
            
//            将获取到数据赋值给当前账号
                self.userAccount?.screen_name = dict["screen_name"] as? String
                self.userAccount?.avatar_large = dict["avatar_large"] as? String
//                将当前对象保存到沙盒中
                self.saveUserAccount()
                loadUserInfoCallBack(error: nil)
            }
            }) { (task, error) in
                loadUserInfoCallBack(error: error)
        }
        
        
        
    }
}

